<?php

namespace App\Supports\Auth\Sms;

use App\Models\User;
use App\Supports\Sms\Sms;

class SmsLogger
{
	public function __construct()
	{
		request()->validate([
			'phone' => 'required|phone:CN,mobile',
			'sms_key' => 'required|string',
			'sms_code' => $this->validateSmsCode(),
			'agreement' => $this->validateAgreement(),
		], [], [
			'invite_code' => '邀请码',
			'sms_key' => '短信验证码密钥',
			'sms_code' => '短信验证码',
			'agreement' => '用户协议'
		]);
	}
	
	protected function validateSmsCode()
	{
		return [
			'required',
			'string',
			function ($attribute, $value, $fail) {
				$sms = app(Sms::class);
				$verification = $sms->isSmsDataRight(request('sms_key'), request('phone'), $value);
				if (! $verification) {
					return $fail('短信验证码无效');
				}
			}
		];
	}
	
	protected function validateAgreement()
	{
		return [
			'required',
			'boolean',
			function ($attribute, $value, $fail) {
				if (! $value) {
					return $fail('请先阅读用户协议');
				}
			}
		];
	}
	
	protected function getExistingUser()
	{
		return User::query()->where('phone', request('phone'))->first();
	}
	
	protected function loginBySelf(User $user)
	{
		return $user;
	}
	
	public function signin()
	{
		if ($user = $this->getExistingUser()) {
			return $this->loginBySelf($user);
		}
		
		return register()->signup();
	}
}
